package com.tian.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.tian.common.enums.SendEmailTypeEnums;
import com.tian.common.factory.ApplicationContextFactory;
import com.tian.common.util.RabbitMQConstant;
import com.tian.mq.message.SendEmailMessage;
import com.tian.service.market.SendEmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * {@code @description:} 发送邮件消费者
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-08-13 21:59
 * {@code @version:} 1.0
 */
@RabbitListener(queues = RabbitMQConstant.SEND_EMAIL_QUEUE)
@Component
@Slf4j
public class SendEmailConsumer {

    @RabbitHandler
    public void process(Object data, Channel channel, Message message) throws IOException {
        log.info("发送邮件消费者收到消息：{}", message.getBody());
        SendEmailMessage sendEmailMessage = JSON.parseObject(new String(message.getBody()), SendEmailMessage.class);
        if (sendEmailMessage == null) {
            log.info("发送邮件消费者收到消息,消息内容：{}", message.getBody());
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            return;
        }
        int type = sendEmailMessage.getType();
        try {
            SendEmailService sendEmailService = ApplicationContextFactory.getBean(SendEmailTypeEnums.getServiceNameByType(type), SendEmailService.class);
            Boolean result = sendEmailService.sendEmail(sendEmailMessage);
            if (result) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }
            log.info("发送邮件消费者收到消息,发送失败,消息内容：{}", message.getBody());
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        } catch (Exception e) {
            log.error("发送邮件失败：{}", e.getMessage());
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
    }
}
